<template>
  <el-row type="flex">
    <el-col class="filter-col" v-show="inputType.firstShow">
      <div>
        <span class="filter-col-title">{{ inputType.firsttitle }}</span>
      </div>
      <div class="filter-input-item">
        <span class="filter-item-title">{{ inputType.firstFilterone }}</span>
        <el-select
          v-model="treeData"
          :placeholder="$t('请选择')"
          :clearable="clearable"
          ref="groupselect"
          class="grouptree"
          @clear="handleClear"
        >
          <el-option :value="treeDataValue" style="height: auto">
            <el-tree
              ref="tree"
              :data="inputType.type == 0 ? resourceGroup : programGroup"
              :props="groupProps"
              @node-click="nodeClick"
            />
          </el-option>
        </el-select>
      </div>
      <div class="filter-input-item">
        <span class="filter-item-title">{{ inputType.firstFiltertwo }}</span>
        <el-select
          v-model="form.resName"
          :clearable="clearable"
          :placeholder="$t('请选择')"
        >
          <el-option
            v-for="item in resourceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
    </el-col>

    <el-col class="filter-col" v-if="inputType.secondShow">
      <div>
        <span class="filter-col-title">{{ $t('选择终端分组') }}</span>
      </div>
      <div class="filter-input-item">
        <span class="filter-item-title">{{ $t('终端分组') }}</span>
        <el-select-tree
          ref="terminalTree"
          :placeholder="$t('请选择')"
          :data="terminalGroup"
          :props="terminalrops"
          v-model="form.terminalList"
          :check-strictly="checkStrictly"
          :default-expand-all="defaultExpandAll"
          :clearable="clearable"
          :multiple="true"
        ></el-select-tree>
      </div>
      <div class="filter-input-button">
        <el-button @click="checkAll">{{ $t('全选') }}</el-button>
        <el-button @click="clearAll">{{ $t('全不选') }}</el-button>
      </div>
    </el-col>

    <el-col class="filter-col" v-if="inputType.thirdShow">
      <div>
        <span class="filter-col-title">{{ $t('选择统计区间') }}</span>
      </div>
      <div class="filter-input-item">
        <span class="filter-item-title">{{ $t('开始日期') }}</span>
        <el-date-picker
          v-model="form.startDate"
          type="date"
          :placeholder="$t('选择日期')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </div>
      <div class="filter-input-item">
        <span class="filter-item-title">{{ $t('结束日期') }}</span>
        <el-date-picker
          v-model="form.endDate"
          type="date"
          :placeholder="$t('选择日期')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="{
            disabledDate(time) {
              if (!form.startDate) return false
              return (
                time.getTime() <
                new Date(form.startDate).getTime() - 3600000 * 24
              )
            },
          }"
        ></el-date-picker>
      </div>
    </el-col>
    <el-col class="filter-export-buttons" v-if="inputType.lastShow">
      <div>
        <el-button type="primary" @click="handleCount" size="small">{{
          $t('数据统计')
        }}</el-button>
      </div>
      <div class="filter-export-button">
        <download-excel
          type="primary"
          class="export-excel-wrapper"
          :fetch="handleExport"
          :fields="excelDataFields"
          :worksheet="worksheet"
          :name="excelFileName"
        >
          <el-button type="primary" size="small">{{
            $t('导出表格')
          }}</el-button>
        </download-excel>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import MediaApi from '@/api/media'
import DeviceApi from '@/api/device'
import SystemApi from '@/api/system'
import DownloadExcel from 'vue-json-excel'
import { deepClone } from '@/utils/index'

export default {
  name: 'CountFilter',
  props: {
    inputType: {
      type: Object,
      default() {
        return {
          type: 0,
          firsttitle: '',
          firstFilterone: '',
          firstFiltertwo: '',
          firstShow: true,
          secondShow: true,
          thirdShow: true,
          lastShow: true,
        }
      },
      terminalGroup: {
        type: Array,
        default() {
          return []
        },
      },
    }
  },
  data() {
    return {
      treeData: '',
      treeDataValue: '',
      checkStrictly: true,
      clearable: true,
      defaultExpandAll: false,
      props: { multiple: true, expandTrigger: 'hover' },
      form: {
        resGroup: '',
        resName: '',
        startDate: '',
        endDate: '',
        terminalList: [],
      },
      groupProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        // disabled(data,node) {

        //   if(typeof data.id === 'undefined'||data.id===''){
        //     return true
        //   }else{
        //     return false
        //   }
        // },
      },
      terminalrops: {
        value: 'id',
        label: 'name',
        children: 'children',
      },
      checkTerminal: [],
      resourceGroup: [
        {
          id: 0,
          name: this.$t('我的媒体'),
          children: [],
        },
        {
          id: -1,
          name: this.$t('下级用户媒体'),
          children: [],
        },
        {
          id: -2,
          name: this.$t('其他媒体'),
          _isOther: true,
          children: [],
        },
      ],
      programGroup: [
        {
          id: 0,
          name: this.$t('我的节目'),
          children: [],
        },
        {
          id: -1,
          name: this.$t('下级用户节目'),
          children: [],
        },
        {
          id: -2,
          name: this.$t('其他节目'),
          _isOther: true,
          children: [],
        },
      ],
      resourceList: [],
      terminalGroup: [],
      worksheet: this.$t('媒体使用统计数据'),
      excelFileName: this.$t('媒体使用统计数据.xls'),
      excelDataFields: {
        终端名称: 'terminalName',
        终端MAC: 'terminalMac',
        播放次数: 'playCount',
      },
      checkGroupArray: []
    }
  },
  components: { DownloadExcel },
  computed: {
    countType: {
      get() {
        return this.inputType
      },
    },
  },
  mounted() {
    this.$nextTick(function () {
      this.initDate()
      this.getMediaGroup()
      this.getTerminalData()
    })
  },
  watch: {
    inputType(val) {
      if (val.type === 1) {
        this.worksheet = this.$t('媒体使用统计数据')
        this.excelFileName = this.$t('媒体使用统计数据.xls')
        this.excelDataFields = {
          终端名称: 'terminalName',
          终端MAC: 'terminalMac',
          播放次数: 'playCount',
        }
      }
    }
  },
  methods: {
    initDate() {
      this.form.startDate = getFormatDate(new Date())
      this.form.endDate = getFormatDate(new Date())
      // this.form.startDate = getFormatDate(
      //   new Date(new Date() - 3600 * 1000 * 24 * 30)
      // )
    },
    initTableData() {
      if (this.countType.type == 0) {
        this.worksheet = this.$t('媒体使用统计数据')
        this.excelFileName = this.$t('媒体使用统计数据.xls')
        this.excelDataFields = {
          终端名称: 'terminalName',
          终端MAC: 'terminalMac',
          播放次数: 'playCount',
        }
      } else if(this.countType.type == 1){
        this.worksheet = this.$t('节目下载统计数据')
        this.excelFileName = this.$t('节目下载统计数据.xls')
        this.excelDataFields = {
          终端名称: 'terminalName',
          分组名称: 'groupName',
          终端MAC: 'terminalMac',
          节目名称: 'name',
          素材总数: 'mediaCount',
          已下载的素材数: 'downloaded',
        }
      } else if(this.countType.type == 2){
        this.worksheet = this.$t('用户扫码统计数据')
        this.excelFileName = this.$t('用户扫码统计数据.xls')
        this.excelDataFields = {
          媒体名称: 'mediaName',
          终端MAC: 'terminalMac',
          屏幕名称: 'screenName',
          节目名称: 'programName',
          车辆编号: 'carNo',
          扫码次数: 'scanCount',
        }
      }
    },
    //获取媒体/节目分组
    async getMediaGroup() {
      let params = {}
      if (this.countType.type == 0) {
        params.type = 1
      } else if (this.countType.type == 2) {
        params.type = 3
      } else if (this.countType.type == 1) {
        params.type = 3
      }
      const mine = await MediaApi.getCatalogue(params)
      const other = await MediaApi.getOtherMedia(params)
      const follow = await MediaApi.getFollow(params)
      if (mine) {
        if (this.countType.type == 0) {
          this.resourceGroup[0].children = mine
        } else {
          this.programGroup[0].children = mine
        }
      }
      if (follow) {
        if (this.countType.type == 0) {
          this.resourceGroup[1].children = follow
        } else {
          this.programGroup[1].children = follow
        }
      }
      if (other) {
        if (this.countType.type == 0) {
          this.resourceGroup[2].children = other
        } else {
          this.programGroup[2].children = other
        }
      }
    },
    //媒体/节目资源列表请求
    async nodeClick(data, node, nodeData) {
      if (data.id === -1 || data.id === -2) {
        return
      }
      this.handleClear()
      this.$refs.groupselect.blur()
      this.treeDataValue = data
      this.treeData = data.name
      this.form.resGroup = data.id ? data.id : 0
      console.log('nodeClick ------------------', this.form.resGroup)
      if (this.countType.type == 0) {
        let param = {
          folderId: data.id ? data.id : 0,
          userId: data.ownerUserId,
        }
        if (data.ownerUserId) {
          param.ownerUserId = data.ownerUserId
        }
        param.size = 9999
        param.current = 1
        const res = await MediaApi.get(param)
        if (res) {
          this.resourceList = res.records ? res.records : []
        }
      } else {
        let params = {
          folderId: data.id ? data.id : 0,
        }
        if (data.ownerUserId) {
          params.ownerUserId = data.ownerUserId
        }
        params.size = 9999
        params.current = 1
        const res = await MediaApi.getProgram(params)
        if (res) {
          this.resourceList = res.records ? res.records : []
        }
      }
    },
    async getTerminalData() {
      const res = await DeviceApi.loadTree()
      if (res) {
        this.terminalGroup = res
      }
    },
    checkAll() {
      this.checkGroupArray = []
      this.getCheckGroup(this.terminalGroup, this.checkGroupArray)
      this.$refs.terminalTree.$refs.elTree.setCheckedNodes(this.checkGroupArray)
    },
    clearAll() {
      this.form.terminalList = []
      this.$refs.terminalTree.$refs.elTree.setCheckedNodes([])
    },
    getCheckGroup(terminalGroup, resultArray) {
      terminalGroup.forEach((element) => {
        this.checkGroupArray.push(element)
        if (element.children) {
          this.getCheckGroup(element.children)
        }
      })
    },
    onSubmit() {},
    handleCount() {
      this.$emit('handle-count', this.form)
    },

    async handleExport() {
      this.initTableData()
      console.log('loadMediaCountList -------', this.form)
      if (
        this.form.resGroup === null ||
        typeof this.form.resGroup === 'undefined' ||
        this.form.resGroup === ''
      ) {
        if (this.inputType.type == 0) {
          this.$alert(this.$t('提示'), this.$t('请先选择正确的媒体分组'))
        } else {
          this.$alert(this.$t('提示'), this.$t('请先选择正确的节目分组'))
        }
        return
      }
      if (!this.form.resName) {
        this.$alert(this.$t('提示'), this.$t('请先选择正确的资源'))
        return
      }
      if (!this.form.terminalList || this.form.terminalList.length === 0) {
        this.$alert(this.$t('提示'), this.$t('请先选择终端分组'))
        return
      }
      if (!this.form.startDate || this.form.startDate === null) {
        this.$alert(this.$t('提示'), this.$t('请选择开始时间'))
        return
      }
      const startTime = new Date(this.form.startDate).getTime()
      const endTime = new Date(this.form.endDate).getTime()
      if (startTime > endTime) {
        this.$alert(this.$t('提示'), this.$t('开始时间不能大于结束时间'))
        return
      }
      let requestParams = {}
      requestParams.beginDate = this.form.startDate
      requestParams.endDate = this.form.endDate
      requestParams.terminalGroupIds = this.form.terminalList
      requestParams.current = 1
      requestParams.size = 10000
      let res
      if (this.inputType.type == 0) {
        requestParams.mediaGroupId = this.form.resGroup
        requestParams.mediaResourcesId = this.form.resName
        res = await SystemApi.loadMediaPlayCount(requestParams)
      } else if(this.inputType.type == 1){
        requestParams.programGroupId = this.form.resGroup
        requestParams.programResourcesId = this.form.resName
        res = await SystemApi.loadProgramDownloadCount(requestParams)
      } else if(this.inputType.type == 2){
         requestParams.programId = this.form.resName
        res = await SystemApi.loadUserScanCount(requestParams)
      }
      return res.data ? res.data.records : []
    },
    handleClear() {
      this.form.resName = ""
    },
  },
}
function getFormatDate(date) {
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  var currentDate = date.getFullYear() + '-' + month + '-' + strDate
  return currentDate
}
</script>
<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.el-row {
  margin-right: 200px;
}
.filter-col {
  display: flex;
  flex-direction: column;
  border: 1px solid $bg-e9;
  min-height: 125px;
  width: 100%;
  margin-right: 30px;
  max-width: 450px;
  min-width: 250px;
  padding-right: 24px;
  .filter-col-title {
    position: relative;
    top: -10px;
    background: $bg-ff;
    margin-left: 16px;
    font-size: 14px;
    padding: 0 4px;
  }
  .filter-input-item {
    display: flex;
    flex-direction: row;
    margin-top: 10px;
    margin-left: 20px;
    .filter-item-title {
      text-align: center;
      padding-top: 10px;
      margin-right: 20px;
      min-width: 60px;
      font-size: $font-size;
      color: #666666;
    }
    ::v-deep .el-input__icon {
      width: 25px;
      line-height: 30px;
    }
  }
  .filter-input-button {
    display: flex;
    flex-direction: row;
    margin-left: 100px;
    margin-top: 10px;
    .el-button {
      width: 60px;
      height: 30px;
      padding: 0;
      font-size: 12px;
    }
    .el-button--medium {
      padding: 0 10px;
    }
  }
  .el-cascader {
    width: 100%;
    max-width: 300px;
    margin: 0, 10px;
  }
  .el-select {
    width: 80%;
    max-width: 300px;
    margin: 0, 10px;
    min-width: 80px;
  }
  .el-select-tree {
    width: 100%;
    min-width: 80px;
  }
  /** 时间筛选框大小 */
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
    max-width: 300px;
    margin: 0, 10px;
    min-width: 80px;
  }
}

.filter-export-buttons {
  margin-top: 30px;
  width: 110px;
  .filter-export-button {
    margin-top: 10px;
  }
}
::v-deep .el-tree-node {
  padding-left: 0;
}
.el-select-dropdown__item {
  padding: 0 10px;
  .selected {
    background: #fff;
  }
}
::v-deep.el-tree-node__label {
  padding-right: 15px;
}
::v-deep.el-input--medium .el-input__icon {
  line-height: 30px !important;
}
</style>